<template>
  <PageContainer
    title="司机管理"
    :actions="pageActions"
    :columns="columns"
    :data-source="driverList"
    :loading="loading"
    :pagination-data="pagination"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 筛选条件 -->
    <template #filter-items>
      <!-- 超级管理员在全部站点模式下显示站点筛选器 -->
      <a-form-item
        v-if="
          userStore.userInfo?.role === 'SUPER_ADMIN' &&
          userStore.userInfo?.siteId === null
        "
        label="所属站点"
      >
        <a-select
          v-model:value="queryParams.siteId"
          placeholder="全部站点"
          style="width: 160px"
          allowClear
          :loading="siteLoading"
        >
          <a-select-option
            v-for="site in siteOptions"
            :key="site.id"
            :value="site.id"
          >
            {{ site.siteName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="司机状态">
        <a-select
          v-model:value="queryParams.driverStatus"
          placeholder="全部状态"
          style="width: 150px"
          allowClear
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option
            v-for="option in statusOptions"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="关键词">
        <a-input
          v-model:value="queryParams.keyword"
          placeholder="姓名、工号、电话"
          style="width: 200px"
          allowClear
        />
      </a-form-item>
    </template>

    <!-- 表格内容 -->
    <template #bodyCell="{ column, record }">
      <!-- 工号 -->
      <template v-if="column.key === 'driverNo'">
        <a class="driver-link" @click="handleView(record)">{{
          record.driverNo
        }}</a>
      </template>

      <!-- 姓名 -->
      <template v-else-if="column.key === 'name'">
        <div style="font-weight: 500">{{ record.name }}</div>
        <div class="phone-text">{{ record.phone }}</div>
      </template>

      <!-- 驾驶证 -->
      <template v-else-if="column.key === 'license'">
        <div>{{ record.licenseType }}</div>
        <div
          class="license-expire"
          :class="getExpireClass(record.licenseExpireDate)"
        >
          到期：{{ formatDate(record.licenseExpireDate) }}
        </div>
      </template>

      <!-- 司机状态 -->
      <template v-else-if="column.key === 'driverStatus'">
        <a-tag :color="getDriverStatusColor(record.driverStatus)">
          {{ getDriverStatusLabel(record.driverStatus) }}
        </a-tag>
      </template>

      <!-- 站点信息（超级管理员全部站点视角显示） -->
      <template v-else-if="column.key === 'site'">
        <span v-if="getSiteName(record.siteId)">{{
          getSiteName(record.siteId)
        }}</span>
        <span v-else class="text-secondary">-</span>
      </template>

      <!-- 操作 -->
      <template v-else-if="column.key === 'action'">
        <a-space>
          <a-button type="link" size="small" @click="handleView(record)"
            >查看</a-button
          >
          <a-button
            type="link"
            size="small"
            @click="handleEdit(record)"
            v-permission="($route?.meta as any)?.$actions?.['edit']?.code"
            >编辑</a-button
          >
          <a-button type="link" size="small" @click="handleViewOrders(record)"
            >查看订单</a-button
          >
          <a-popconfirm
            title="确定删除该司机吗？"
            @confirm="handleDelete(record)"
            v-permission="($route?.meta as any)?.$actions?.['delete']?.code"
          >
            <a-button type="link" size="small" danger>删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message, Modal } from "ant-design-vue";
import { PlusOutlined, ExportOutlined } from "@ant-design/icons-vue";
import PageContainer from "@/components/business/PageContainer.vue";
import { getDriverList, deleteDriver } from "@/api/tenant/driver";
import { getSiteList } from "@/api/tenant/site";
import { useUserStore } from "@/stores/user";
import type { Driver } from "@/types/driver";
import type { Site } from "@/types/site";
import { formatDate } from "@/utils/format";
import { useDictionary } from "@/composables/useDictionary";
import dayjs from "dayjs";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 字典
const {
  getLabel: getDriverStatusLabel,
  loadDictionaries: loadDriverStatuses,
  options: statusOptions,
} = useDictionary("DRIVER_STATUS");

const queryParams = reactive({
  current: 1,
  size: 10,
  driverStatus: "",
  keyword: "",
  siteId: undefined as number | undefined,
});

const driverList = ref<Driver[]>([]);
const loading = ref(false);
const siteOptions = ref<Site[]>([]);
const siteLoading = ref(false);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ["10", "20", "50", "100"],
});

// 页面操作按钮配置
const pageActions = computed(() => [
  {
    key: "create",
    label: "新增司机",
    type: "primary" as const,
    icon: PlusOutlined,
    permission: (route.meta as any)?.$actions?.create?.code,
    onClick: handleCreate,
  },
  {
    key: "export",
    label: "导出",
    icon: ExportOutlined,
    onClick: () => {
      message.info("导出功能开发中");
    },
  },
]);

const columns = computed(() => {
  const baseColumns: any[] = [
    { title: "工号", dataIndex: "driverNo", key: "driverNo", width: 120 },
    { title: "姓名/电话", key: "name", width: 150 },
    { title: "身份证号", dataIndex: "idCard", key: "idCard", width: 160 },
    { title: "驾驶证类型/到期", key: "license", width: 180 },
    { title: "状态", key: "driverStatus", width: 100 },
    { title: "入职日期", dataIndex: "entryDate", key: "entryDate", width: 120 },
  ];

  // 超级管理员在全部站点模式下显示站点列
  const isViewingAllSites =
    userStore.userInfo?.role === "SUPER_ADMIN" &&
    userStore.userInfo?.siteId === null;
  if (isViewingAllSites) {
    baseColumns.splice(5, 0, { title: "所属站点", key: "site", width: 120 });
  }

  baseColumns.push({
    title: "操作",
    key: "action",
    fixed: "right",
    width: 260,
  });

  return baseColumns;
});

const fetchDriverList = async () => {
  loading.value = true;
  try {
    const currentSiteId = userStore.userInfo?.siteId;

    const response = await getDriverList({
      ...queryParams,
      current: pagination.current,
      size: pagination.pageSize,
      // 司机站点隔离：
      // 1. 如果用户选择了具体站点，使用用户当前站点
      // 2. 如果是超级管理员全部站点模式，使用筛选器选择的站点（可能为空，表示查询所有）
      siteId: currentSiteId || queryParams.siteId,
    });

    const data = response.data as any;
    driverList.value = data.records || [];
    pagination.total = data.total || 0;
  } catch (error: any) {
    console.error("获取司机列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchDriverList();
};

const handleReset = () => {
  Object.assign(queryParams, {
    driverStatus: "",
    keyword: "",
  });
  pagination.current = 1;
  fetchDriverList();
};

const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchDriverList();
};

const handleCreate = () => {
  router.push("/tenant/driver/create");
};

const handleView = (record: Driver) => {
  router.push(`/tenant/driver/${record.id}`);
};

const handleEdit = (record: Driver) => {
  router.push(`/tenant/driver/edit/${record.id}`);
};

const handleViewOrders = (record: Driver) => {
  router.push({
    path: "/tenant/order",
    state: {
      driverId: record.id,
      driverName: record.name,
      fromNavigation: true, // 标记是从导航跳转而来
    },
  });
};

const handleDelete = (record: Driver) => {
  Modal.confirm({
    title: "删除司机",
    content: `确定要删除司机 ${record.name} 吗？`,
    okText: "确定删除",
    okType: "danger",
    onOk: async () => {
      try {
        await deleteDriver(record.id);
        message.success("司机删除成功");
        fetchDriverList();
      } catch (error: any) {
        console.error("删除司机失败:", error);
        if (error.message && error.message !== "Error") {
          message.error(error.message);
        }
      }
    },
  });
};

const getExpireClass = (date: string) => {
  const daysLeft = dayjs(date).diff(dayjs(), "day");
  if (daysLeft < 0) return "expire-overdue";
  if (daysLeft <= 30) return "expire-warning";
  return "expire-normal";
};

// 获取司机状态颜色
const getDriverStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    IDLE: "green",
    BUSY: "blue",
    VACATION: "orange",
    RESIGNED: "red",
    RESTING: "cyan",
    TRAINING: "purple",
    STANDBY: "gold",
    SICK_LEAVE: "magenta",
  };
  return colorMap[status] || "default";
};

// 根据站点ID获取站点名称
const getSiteName = (siteId?: number) => {
  if (!siteId) return "";
  const site = siteOptions.value.find((s) => s.id === siteId);
  return site?.siteName || "";
};

// 加载站点列表
const loadSites = async () => {
  siteLoading.value = true;
  try {
    const response = await getSiteList();
    siteOptions.value = (response.data as any) || [];
  } catch (error) {
    console.error("获取站点列表失败:", error);
  } finally {
    siteLoading.value = false;
  }
};

onMounted(() => {
  loadDriverStatuses();
  loadSites();
  fetchDriverList();
});
</script>

<style scoped>
/* 自定义样式 */

.driver-link {
  color: var(--primary-color);
  font-weight: 600;
  font-family: monospace;
  cursor: pointer;
}

.driver-link:hover {
  color: var(--primary-hover);
  text-decoration: underline;
}

.phone-text {
  color: var(--text-secondary);
  font-size: 12px;
  margin-top: 2px;
}

.license-expire {
  font-size: 12px;
  margin-top: 2px;
}

.expire-normal {
  color: var(--text-secondary);
}

.expire-warning {
  color: var(--warning-color);
  font-weight: 500;
}

.expire-overdue {
  color: var(--error-color);
  font-weight: 500;
}

.plate-number {
  font-family: monospace;
  font-weight: 600;
  color: var(--text-primary);
}

.text-secondary {
  color: var(--text-secondary);
}
</style>
